/*
 * Copyright 2009 BioTeam Inc
 * 
 * Licensed under License GNU LESSER GENERAL PUBLIC LICENSE version 3.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.gnu.org/copyleft/lesser.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package net.bioteam.appweb.model;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import net.bioteam.appweb.Config;
import bsh.BshMethod;
import bsh.Interpreter;
import bsh.NameSpace;

public class BeanshellProgramModifier implements ProgramModifier {

	NameSpace ns;
	long modTime;
	File file;
	public BeanshellProgramModifier() throws Exception
	{
		file = new File(Config.topdir + "/conf/bshmodifier.bsh");
		load(file);
	}
	
	private synchronized void load(File file) throws Exception
	{
		BufferedReader reader=new BufferedReader(new FileReader(file));
		String line;
		StringBuffer sb=new StringBuffer();
		while ((line=reader.readLine())!=null)
		{
			sb.append(line).append("\n");
		}
		String statements=sb.toString();
		modTime=file.lastModified();
		reader.close();
		Interpreter bsh = new Interpreter();
		ClassLoader tcl = Thread.currentThread().getContextClassLoader();
		bsh.getClassManager().setClassLoader(tcl);
		bsh.eval(statements);
		
		ns=bsh.getNameSpace();
		Class[] sig=new Class[1];
		sig[0]=Program.class;
	
		BshMethod method=ns.getMethod("modifyProgram", sig);
		if (method==null)
		{
			throw new Exception(" could not modifyProgram method in "+file.getAbsolutePath());
		}
		
		
		
	}
	public void modifyProgram(Program program)
			throws Exception {
		if (file.lastModified()!=modTime)
		{
			load(file);
		}
		Interpreter bsh = new Interpreter();
		bsh.setNameSpace(ns);
		bsh.set("program", program);
		bsh.eval("modifyProgram(program)");
	}

}
